#!/bin/sh -ef
#
# Copyright (C) 2003-2019  Dmitry V. Levin <ldv@altlinux.org>
# 
# The hsh-rmchroot utility for the hasher project
#
# SPDX-License-Identifier: GPL-2.0-or-later
#

. hsh-sh-functions

show_help()
{
	cat <<EOF
hsh-rmchroot - remove hasher chroot created by hsh-mkchroot.

Usage: $PROG [options] [<path-to-workdir>]

<path-to-workdir> must be valid hasher directory.

Options:
  --hasher-priv-dir=DIR     hasher-priv directory;
  --number=NUMBER           subconfig identifier;
  --wait-lock               wait for workdir and hasher-priv locks;
  --no-wait-lock            do not wait for workdir and hasher-priv locks;
  -q, --quiet               try to be more quiet;
  -v, --verbose             print a message for each action;
  -V, --version             print program version and exit;
  -h, --help                show this text and exit.
    
Report bugs to http://bugs.altlinux.ru/

EOF
	exit
}

TEMP=`getopt -n $PROG -o $getopt_common_opts -l hasher-priv-dir:,no-lock,number:,wait-lock,no-wait-lock,$getopt_common_longopts -- "$@"` ||
	show_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		--hasher-priv-dir)
			hasher_priv_dir="$(opt_check_dir "$1" "$2")"
			shift
			;;
		--no-lock) no_lock=1
			;;
		--number)
			number="$(opt_check_number_ge_0 "$1" "$2")"
			shift
			;;
		--wait-lock) lock_nowait=
			;;
		--no-wait-lock) lock_nowait=1
			;;
		--) shift; break
			;;
		*) parse_common_option "$1"
			;;
	esac
	shift
done

if [ -z "$workdir" ]; then
	# Exactly one argument.
	[ "$#" -ge 1 ] || show_usage 'Insufficient arguments.'
	[ "$#" -le 1 ] || show_usage 'Too many arguments.'
else
	# At most one argument.
	[ "$#" -le 1 ] || show_usage 'Too many arguments.'
fi

if [ "$#" -ge 1 ]; then
	set_workdir "$1"
	shift
else
	set_workdir
fi

lock_workdir

cd chroot
verbose "Changed working directory to \`$chroot'."
deduce_lock_hasher_priv

mkdir -p -m711 $verbose .host >&2
install_static_helper ash sh
install_static_helper find
verbose 'Installed .host programs.'

if [ ! -c "dev/null" ]; then
	ugid1="$("$getugid1" ${number:+-$number})" ||
		fatal 'getugid1 failed.'
	gid1="$(printf %s "$ugid1" |cut -d: -f2)"

	mkdir -p -m755 $verbose dev >&2
	chgrp "$gid1" $verbose . dev >&2
fi

cat >.host/entry <<__EOF__
#!/.host/sh${verbose:+ -x}
/.host/sh -c ':>/dev/null' && exec >/dev/null 2>&1
chmod -Rf u+rwX -- /* /.out
/.host/find / -depth -delete
exit 0
__EOF__
chmod 755 .host/entry

wlimit_time_elapsed=$wlimit_time_long wlimit_time_idle=$wlimit_time_long \
    chrootuid2 </dev/null &&
	verbose 'Removed files owned by user2.' ||
	fatal 'Failed to remove files owned by user2.'

wlimit_time_elapsed=$wlimit_time_long wlimit_time_idle=$wlimit_time_long \
    chrootuid1 </dev/null &&
	verbose 'Removed files owned by user1.' ||
	fatal 'Failed to remove files owned by user1.'

rm -rf $verbose -- "$chroot" >&2 ||
	fatal 'Failed to remove some files.'
